from pydantic import BaseModel, Field, HttpUrl
from typing import Optional, List
from datetime import datetime


class ServiceConfigBase(BaseModel):
    name: str = Field(..., min_length=1, max_length=100, description="服务名称")
    primary_url: HttpUrl = Field(..., description="主服务URL")
    backup_url: HttpUrl = Field(..., description="备份服务URL")
    health_check_endpoint: str = Field(default="/health", description="健康检查端点")
    check_interval: int = Field(default=30, ge=5, le=3600, description="检查间隔(秒)")
    timeout: int = Field(default=10, ge=1, le=300, description="超时时间(秒)")
    retry_count: int = Field(default=3, ge=1, le=10, description="重试次数")
    is_active: bool = Field(default=True, description="是否激活")
    description: Optional[str] = Field(None, max_length=500, description="服务描述")


class ServiceConfigCreate(ServiceConfigBase):
    pass


class ServiceConfigUpdate(BaseModel):
    name: Optional[str] = Field(None, min_length=1, max_length=100)
    primary_url: Optional[HttpUrl] = None
    backup_url: Optional[HttpUrl] = None
    health_check_endpoint: Optional[str] = None
    check_interval: Optional[int] = Field(None, ge=5, le=3600)
    timeout: Optional[int] = Field(None, ge=1, le=300)
    retry_count: Optional[int] = Field(None, ge=1, le=10)
    is_active: Optional[bool] = None
    description: Optional[str] = Field(None, max_length=500)


class ServiceConfigResponse(ServiceConfigBase):
    id: int
    created_at: datetime
    updated_at: datetime

    class Config:
        from_attributes = True


class HealthCheckResponse(BaseModel):
    id: int
    service_id: int
    status: str
    response_time: Optional[float]
    http_status: Optional[int]
    error_message: Optional[str]
    checked_at: datetime

    class Config:
        from_attributes = True


class SwitchLogResponse(BaseModel):
    id: int
    service_id: int
    switch_type: str
    from_status: str
    to_status: str
    reason: Optional[str]
    operator: Optional[str]
    success: bool
    error_message: Optional[str]
    created_at: datetime

    class Config:
        from_attributes = True


class ServiceStatus(BaseModel):
    service_id: int
    service_name: str
    current_status: str  # primary, backup
    health_status: str  # healthy, unhealthy, unknown
    last_check_time: Optional[datetime] = None
    last_switch_time: Optional[datetime] = None
    total_switches: int
    uptime_percentage: Optional[float] = None


class HealthCheckRequest(BaseModel):
    service_id: int
    force_check: bool = False


class SwitchRequest(BaseModel):
    service_id: int
    target_status: str = Field(..., pattern="^(primary|backup)$", description="目标状态")
    reason: Optional[str] = Field(None, max_length=500, description="切换原因")
    operator: Optional[str] = Field(None, max_length=100, description="操作人")


class SwitchResponse(BaseModel):
    success: bool
    message: str
    switch_log: Optional[SwitchLogResponse] = None